package com.stroke.resources.loaders;

import com.stroke.core.ConfigurationBuilder;
import com.stroke.graphics.Animation;
import com.stroke.tools.animation.AnimationFile;
import org.apache.log4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Author: Igor Bubelov
 * Date: 3/13/11 5:40 PM
 */
public class GraphicResourcesLoader {
    public static Map<String, Animation> load(File config) {
        final Map<String, Animation> result = new HashMap<String, Animation>();

        XMLReader reader;

        try {
            reader = XMLReaderFactory.createXMLReader();
        } catch (SAXException ex) {
            Logger.getLogger(GraphicResourcesLoader.class).error("Failed to create XML reader", ex);
            return null;
        }

        DefaultHandler handler = new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (qName.equals("resource")) {
                    String name = attributes.getValue("name");
                    String type = attributes.getValue("type");
                    String path = attributes.getValue("path");

                    if (type.equals("image")) {
                        //TODO
                    } else if (type.equals("animation")) {
                        AnimationFile animationFile = new AnimationFile(path);
                        Animation animation = new Animation(animationFile);
                        result.put(name, animation);
                    } else {
                        //TODO
                    }
                }
            }
        };

        reader.setContentHandler(handler);

        try {
            reader.parse(new InputSource(new FileInputStream(config)));
        } catch (Exception ex) {
            Logger.getLogger(GraphicResourcesLoader.class).error("Failed to parse graphics resources configuration", ex);
        }

        return result;
    }
}
